package com.jpaAutoProcess.kernel;

import com.jpaAutoProcess.utils.SqlConvertEntityUtil;
import lombok.NonNull;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @User c.c
 * @Since 2022/8/24
 * @Time 10:46
 * @Description 查询核心
 */

public class QueryKernel<T> {

  public List<T> getTs(@NonNull StringBuilder select, @NonNull StringBuilder from, StringBuilder where, Map<String, Object> params, @NonNull EntityManager entityManager,@NonNull Class targetClass) {
    List<T> ts = new ArrayList<>();

    //初始化sql语句
    StringBuilder sql = SqlConvertEntityUtil.initSql(select, from, where);

    //查询数据
    Query query = entityManager.createNativeQuery(sql.toString());

    if (params!=null&&params.size()>0){
      params.forEach(query::setParameter);
    }

    //封装字段和值 得到List<Map<k,v>> k为属性名 v为数据库值
    List fieldAndValueMapList = SqlConvertEntityUtil.getfieldAndValueMap(SqlConvertEntityUtil.getSelectStringToList(sql), query.getResultList());

    for (Object fieldAndValue : fieldAndValueMapList) {
      T t = null;
      try {
        //反射获取目标类
        t = (T) SqlConvertEntityUtil.reflectionTargetClass((HashMap<String, Object>) fieldAndValue, targetClass);
      } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
      } catch (InstantiationException instantiationException) {
        throw new RuntimeException(instantiationException);
      }
      ts.add(t);
    }
    return ts;
  }

}
